<template>
  <div class="signatureBox-popup" :style="{ 'z-index': zIndex }">
    <div class="popup2">
      <div class="signatureBox">
        <div class="canvasBox" ref="canvasHW">
          <div style="padding-top: 20px" class="input_text">
            请在下面空白区域签名
          </div>
          <div
            style="padding-top: 10px; color: #ff0045; font-size: 12px"
            class="input_text"
          >
            必须由本人签字，违者将承担法律责任
          </div>
          <canvas
            ref="canvasF"
            @touchstart="touchStart"
            @touchmove="touchMove"
            @touchend="touchEnd"
            @mousedown="mouseDown"
            @mousemove="mouseMove"
            @mouseup="mouseUp"
          ></canvas>
          <!-- <div class="btnBox"> -->
          <!-- <div @click="overwrite">重写</div> -->
          <!-- <div @click="commit">提交签名</div> -->
          <!-- </div> -->
        </div>
      </div>
      <div
        style="padding-bottom: 20px; background-color: #fff; text-align: center"
      >
        <button
          style="
            border: none;
            border-radius: 20px;
            color: #fff;
            padding: 5px;
            margin-left: 20px;
            float: left;
            background: #0798ea;
            width: 15%;
          "
          @click="commit"
          type="button"
        >
          确定
        </button>
        <button
          v-if="isContinues"
          style="
            border: none;
            border-radius: 20px;
            color: #fff;
            padding: 5px;
            margin-right: 40px;
            background: #0798ea;
            width: 15%;
          "
          @click="overwrite2"
          type="button"
        >
          继续
        </button>
        <button
          style="
            border: none;
            border-radius: 20px;
            color: #fff;
            padding: 5px;
            background: #b9bfd3;
            width: 15%;
          "
          @click="overwrite"
          type="button"
        >
          清除
        </button>

        <button
          style="
            border: none;
            border-radius: 20px;
            color: #fff;
            padding: 5px;
            margin-right: 20px;
            float: right;
            background: #b9bfd3;
            width: 15%;
          "
          @click="Canvas_goBack"
          type="button"
        >
          取消
        </button>
      </div>
    </div>
    <!-- <div class="popup_title">
            <div class="popup_title_">请输入证书信息</div>
          </div> -->

    <!-- </van-popup> -->
  </div>
</template>
  <script>
  import { getAxios2 } from "@/utils/request2";
import { CommonAttachUploadBase64 } from "@/api/common";
import { Dialog } from "vant";
export default {
  props: {
    mzIndex: {},
    isContinue: {},
    imgMax: {
      //允许图片最大值   默认int最大值
      type: Number,
      default: 9999,
    },
  },
  data() {
    return {
      isContinues: false,
      stageInfo: "",
      zIndex: -8,
      points: [],
      canvasTxt: null,
      imgUrls: [],
    };
  },
  mounted() {
    let canvas = this.$refs.canvasF;
    canvas.height = this.$refs.canvasHW.offsetHeight - 84; //-500
    canvas.width = this.$refs.canvasHW.offsetWidth + 30; //this.$refs.canvasHW.offsetWidth + 230
    this.canvasTxt = canvas.getContext("2d");
    this.stageInfo = canvas.getBoundingClientRect();
  },
  created() {
    if (this.mzIndex) {
      this.zIndex = this.mzIndex;
    }
    if (this.isContinue) {
      this.isContinues = this.isContinue;
    }
    if (this.imgMax) {
      this.imgMax = this.imgMax;
    }
  },
  methods: {
    //mobile
    touchStart(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clienX,
          y: ev.targetTouches[0].clientY,
        };
        this.startX = obj.x;
        this.startY = obj.y;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
      }
    },
    setzIndex(mzIndex) {
      this.zIndex = mzIndex;
      console.log(this.zIndex);
    },
    touchMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - this.stageInfo.left,
          y: ev.targetTouches[0].clientY - this.stageInfo.top,
        };
        this.moveY = obj.y;
        this.moveX = obj.x;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.startY = obj.y;
        this.startX = obj.x;
        this.points.push(obj);
      }
    },
    touchEnd(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - this.stageInfo.left,
          y: ev.targetTouches[0].clientY - this.stageInfo.top,
        };
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
      }
    },
    //pc
    mouseDown(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (1) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.startX = obj.x;
        this.startY = obj.y;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
        this.isDown = true;
      }
    },
    mouseMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (this.isDown) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.moveY = obj.y;
        this.moveX = obj.x;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.startY = obj.y;
        this.startX = obj.x;
        this.points.push(obj);
      }
    },
    mouseUp(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (1) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
        this.points.push({ x: -1, y: -1 });
        this.isDown = false;
      }
    },
    //重写
    overwrite() {
      this.canvasTxt.clearRect(
        0,
        0,
        this.$refs.canvasF.width,
        this.$refs.canvasF.height
      );
      this.points = [];
    },
    overwrite2() {
      this.afterRead(this.$refs.canvasF.toDataURL(), false);
      if (this.imgUrls.length > 0) {
        var imgArry = this.imgUrls.split(";");
        if (imgArry.length >= this.imgMax) {
          isContinues = false;
        }
      }
    },
    // 上传图片
    async afterRead(base64) {
      console.log("afterRead base64")
      var params = {
        Img: base64,
      };
      let params2=new FormData()
      let file =this.base64ImgtoFile(base64)
      params2.append("file",file)
      // params2.append("studyId",Number(localStorage.getItem('userId')))
      params2.append("studyId",Number(localStorage.getItem('data')))//使用保存用户消息返回 的 data 作为 studyId
      // params2.append("studyId",1333333)
      let axios2=await getAxios2()
      const res = await axios2.post(
        `https://hmbm.zatsafety.com/app/study/uploadSignFile`,params2
      )
      console.log(res);
      if(res.msg == 'success'){
        Dialog.alert({
            message: "签名成功",
          }).then(() => {
            // on close
            this.$router.push({path:'/hmbm/btnList'})
          });
      }
          
      // CommonAttachUploadBase64(params)
      //   .then((res) => {
      //     this.imgUrl = res.data.FilePath;
      //     // console.log('111',this.imgUrl)
      //   })
      //   .catch((err) => {
      //     console.log("err", err);
      //   });
    },
    //base64转png
    base64ImgtoFile(dataurl, filename = localStorage.getItem('userId')+'file') {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },
    //提交签名
    commit() {
      // if (this.adds == "MarkSignAttach") {
      //   this.imgUrl = this.$refs.canvasF.toDataURL();
      // } else if (this.adds == "AuditSignAttach") {
      //   this.imgUrl2 = this.$refs.canvasF.toDataURL();
      // } else if (this.adds == "ApproveSignAttach") {
      //   this.imgUrl3 = this.$refs.canvasF.toDataURL();
      // }

      // this.afterRead(this.$refs.canvasF.toDataURL(), true);  //2023.08.23ZQH
      // this.zIndex = -8;//2023.08.23ZQH
      
      // console.log('111',this.points)
      if(this.points.length === 0) {
        Dialog.alert({
          message: "请先签名",
      })
      }else {
        Dialog.confirm({
        title: "确认签名",
        message: "请确认是否提交签名",
      })
        .then(() => {
          this.imgUrl = this.$refs.canvasF.toDataURL();
          console.log(this.imgUrl)
          this.afterRead(this.imgUrl)
       
        })
        .catch(() => {
          // on cancel
        });
      }
     
    },
    Canvas_goBack() {
      this.zIndex = -8;
      this.isCertificate = false;
      this.isCertificate2 = false;
      this.$router.go(-1);
    },
  },
};
</script>
  <style lang="less" scoped>
.popup2 {
  width: 100%;
  height: 100%;
  padding-top: 16px;
  padding-bottom: 16px;
  text-align: center;
  border-radius: 7px;
}
.signatureBox-popup {
  min-height: calc(100vh - 40px);
  background-color: #fff;
  opacity: 1;
  background: #666;
  display: none;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  padding-top: 150px;
}

.signatureBox {
  width: 100%;
  height: calc(100% - 50px);
  box-sizing: border-box;
  overflow: hidden;
  background: #fff;
  height: 60%;
  z-index: 9;
  display: inline-flex;
  flex-direction: column;
}
.canvasBox {
  box-sizing: border-box;
  flex: 1;
  height: 100%;
  text-align: center;
}
</style>
  